//
//  AppDelegate.swift
//  肉荣微博
//
//  Created by king on 15/7/27.
//  Copyright © 2015年 king. All rights reserved.
//

import UIKit

let KINGRootControllerSwitchNSNotification = "KINGRootControllerSwitchNSNotification"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        //第一个print不能省略，可以确保userAccent不为空 ，否则会造成程序崩溃
        //print("加载前\(KINGUserAccount.loadUserInfo())")
        if let _ = KINGUserAccount.loadUserInfo() {
            KINGUserAccount.currentUserAccount().loadUserIcon { () -> () in
                print("重新加载后\(KINGUserAccount.loadUserInfo())")
                    //等待刷新数据之后在调用显示界面，这样可以解决用户中途修改头像问题
                    //可以做图片刷新操作
                }
        }
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchRootController:", name: KINGRootControllerSwitchNSNotification, object: nil)
        self.window?.rootViewController = self.defaultViewController()
        //        window?.rootViewController = KINGWelcomeViewController()
        
        self.window?.backgroundColor = UIColor.whiteColor()
        self.window?.makeKeyAndVisible()
        self.setupAppearance()
        return true
    }
    
    func switchRootController(n:NSNotification) {

        let mainVc = n.object as! Bool

        window?.rootViewController = mainVc ? KINGMainViewController() : KINGWelcomeViewController()
    }
    
    private func defaultViewController() -> UIViewController {
        if KINGUserAccount.isLogin {
            return KINGMainViewController()
        }
        return isSetup() ? KINGNewFeatureController() : KINGWelcomeViewController()
    }
    
    private func isSetup() -> Bool{
        //获取当前版本
        let appInfo = Double(NSBundle.mainBundle().infoDictionary!["CFBundleVersion"] as! String)
        //获取之前版本信息
        let versonKey = "appVersonKey"
        let saveVerson = NSUserDefaults.standardUserDefaults().doubleForKey(versonKey)
        //将当前版本保存到偏好设置中
        NSUserDefaults.standardUserDefaults().setDouble(appInfo!, forKey: versonKey)
        print(appInfo)
        //返回结果
        return appInfo > saveVerson
    }
    
/// 使用外观代理对象对整体进行配置，一旦设置全局有效 应该尽早的进行设置
    private func setupAppearance() {
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

}


